import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:nylo_framework/nylo_framework.dart';
import 'package:video_player/video_player.dart';
import 'package:flick_video_player/flick_video_player.dart';
import 'package:flutter_app/resources/widgets/lottie_animation_widget.dart';

class Player extends StatefulWidget {
  final String url;
  final Function(String url) playFinish; // 播放结束事件
  const Player({super.key, required this.url, required this.playFinish});

  @override
  createState() => _PlayerState();
}

LoadingStyle get loadingStyle => LoadingStyle.normal(
      child: CupertinoActivityIndicator(),
    );

class _PlayerState extends NyState<Player> {
  FlickManager? flickManager;
  late VideoPlayerController videoPlayerController;

  // 视频宽高比
  double aspectRatio = 16 / 9;
  double _bufferingProgress = 0.0; // 缓冲进度 (0.0 - 1.0)
  bool _isBuffering = false;
  @override
  get init => () {};

  Future<void> _initializePlayer() async {
    print("play url:${widget.url}");

    if (widget.url.endsWith(".m3u8")) {
      videoPlayerController =
          VideoPlayerController.networkUrl(Uri.parse(widget.url));
    } else {
      File localfile = File(widget.url);
      if (await localfile.exists()) {
        print('File exists and is ${localfile.lengthSync()} bytes');
        videoPlayerController = VideoPlayerController.file(localfile);
      } else {
        NyLogger.dump("文件不存在", "player");
      }
    }

    await videoPlayerController.initialize();
    print("rate: ${videoPlayerController.value.aspectRatio}");

    setState(() {
      aspectRatio = videoPlayerController.value.aspectRatio;
      flickManager = FlickManager(
        videoPlayerController: videoPlayerController,
        autoPlay: true,
      );
    });

    if (!videoPlayerController.value.isPlaying) {
      videoPlayerController.play();
    }

    videoPlayerController.addListener(_updateBufferingProgress);
    videoPlayerController.addListener(_playFinished);
  }

  void _playFinished() {
    // 播放结束事件
    if (videoPlayerController.value.position >=
        videoPlayerController.value.duration) {
      widget.playFinish(widget.url);
    }
  }

  void _updateBufferingProgress() {
    if (!mounted || !videoPlayerController.value.isInitialized) {
      return;
    }

    final isBufferingNow = videoPlayerController.value.isBuffering;

    // 计算缓冲进度
    final duration = videoPlayerController.value.duration;
    if (duration.inMilliseconds > 0) {
      final buffered = videoPlayerController.value.buffered;
      if (buffered.isNotEmpty) {
        final lastBuffered = buffered.last.end;
        _bufferingProgress =
            lastBuffered.inMilliseconds / duration.inMilliseconds * 100;
        // 保留两位小数
        _bufferingProgress =
            double.parse((_bufferingProgress).toStringAsFixed(2));
      }
    }

    if (isBufferingNow != _isBuffering) {
      setState(() {
        _isBuffering = isBufferingNow;
      });
    } else {
      setState(() {});
    }

    if (!isBufferingNow) {
      setState(() {
        _bufferingProgress = 0;
      });
    }
  }

  @override
  void initState() {
    _initializePlayer();
    super.initState();
  }

  @override
  Widget view(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        AspectRatio(
          aspectRatio: aspectRatio,
          child: Container(
            color: Colors.black,
            child: flickManager != null
                ? FlickVideoPlayer(flickManager: flickManager!)
                : const Center(
                    child: LottieAnimation(
                      url: "public/lotties/movie.json",
                    ),
                  ),
          ),
        ),
        if (_isBuffering)
          AspectRatio(
            aspectRatio: aspectRatio,
            child: Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.4),
              ),
              child: Center(
                child: Text(
                  _isBuffering ? "正在缓冲${_bufferingProgress}%" : "加载中...",
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
              ),
            ),
          ),
      ],
    );
  }

  @override
  void dispose() {
    print("dispose player");
    videoPlayerController.removeListener(_updateBufferingProgress);
    videoPlayerController.removeListener(_playFinished);
    try {
      flickManager?.dispose();
    } finally {
      // videoPlayerController.dispose();
    }
    super.dispose();
  }
}
